package com.linkoog.devtools.code_generator.util;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.wm.WindowManager;

import java.awt.*;

public class ProjectUtils {

    public static Project getCurrentProject() {

        ProjectManager projectManager = ProjectManager.getInstance();
        Project[] openProjects = projectManager.getOpenProjects();
        if (openProjects.length == 0) {
            return projectManager.getDefaultProject();//没有打开项目
        } else if (openProjects.length == 1) {
            // 只存在一个打开的项目则使用打开的项目
            return openProjects[0];
        }else {
            //如果有多个项目，获取窗口处于激活状态的项目
            try {
                WindowManager wm = WindowManager.getInstance();
                for (Project project : openProjects) {
                    Window window = wm.suggestParentWindow(project);
                    if (window != null && window.isActive()) {
                        return project;
                    }
                }
            } catch (Exception ignored) {
            }
        }

        //否则使用默认项目
        return projectManager.getDefaultProject();
    }

}
